package com.gan.yidademo.dormitory.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasHeaders;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasRequest;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasResponse;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gan.yidademo.common.exception.BusinessException;
import com.gan.yidademo.common.util.YiDaUtil;
import com.gan.yidademo.dormitory.mapper.StayOutLateMapper;
import com.gan.yidademo.dormitory.model.StayOutLate;
import com.gan.yidademo.dormitory.service.DormitoryService;
import com.gan.yidademo.leave.service.StuLeaveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author gbw
 * @date 2023/9/22
 */
@Slf4j
@Service
public class DormitoryServiceImpl extends ServiceImpl<StayOutLateMapper, StayOutLate> implements DormitoryService {

    @Value("${DingDing.ak}")
    private String ak;
    @Value("${DingDing.sk}")
    private String sk;
    /**
     * 应用编码
     */
    @Value("${YiDa.dormitory.appType}")
    private String appType;
    /**
     * 应用秘钥
     */
    @Value("${YiDa.dormitory.systemToken}")
    private String systemToken;

    /**
     * 表单ID
     */
    @Value("${YiDa.dormitory.formUuid}")
    private String formUuid;

    /**
     * 用户Id
     */
    @Value("${DingDing.userId}")
    private String userId;


    @Override
    public List<StayOutLate> getFormData() {
        String token = null;
        try {
            token = YiDaUtil.getTokenFromApp(ak, sk);
        } catch (Exception e) {
            throw new BusinessException("获取token失败" + e.getMessage());
        }


        com.aliyun.dingtalkyida_1_0.Client client;
        try {
            client = YiDaUtil.createClient();
        } catch (Exception e) {
            throw new BusinessException("创建宜搭客户端失败!");
        }
        SearchFormDatasHeaders searchFormDatasHeaders = new SearchFormDatasHeaders();
        searchFormDatasHeaders.xAcsDingtalkAccessToken = token;
        SearchFormDatasRequest searchFormDatasRequest = new SearchFormDatasRequest()
                .setAppType(appType)
                .setSystemToken(systemToken)
                .setUserId(userId)
                .setFormUuid(formUuid)
                .setCurrentPage(1)
                .setPageSize(10);
        try {
            SearchFormDatasResponse stuLeaveResp = client.searchFormDatasWithOptions(searchFormDatasRequest, searchFormDatasHeaders, new RuntimeOptions());
            SearchFormDatasResponseBody body = stuLeaveResp.getBody();
            List<SearchFormDatasResponseBody.SearchFormDatasResponseBodyData> data = body.getData();
            List<StayOutLate> lateList = new ArrayList<>();
            for (SearchFormDatasResponseBody.SearchFormDatasResponseBodyData dormitory : data) {
                Map<String, ?> formData = dormitory.getFormData();
                String dormitoryNumber = (String) formData.get("textField_ln1chujz");
                String dormitoryData = (String) formData.get("textField_ln1chujy");
                String ifLate = (String) formData.get("textField_ln1chuk9");
                String remark = (String) formData.get("textareaField_ln1chuk3");
                String submitter = (String) formData.get("textField_ln1chuk4");
                String stuName = (String) formData.get("textField_ln1chuk0");
                String className = (String) formData.get("textField_ln1chuk1");
                Date submissionTime = new Date((Long) formData.get("dateField_ln1chuk6"));

                StayOutLate lateInfo = StayOutLate.builder().dormitory(dormitoryData).dormitoryNumber(dormitoryNumber).ifLate(ifLate).remark(remark)
                        .submitter(submitter).submissionTime(submissionTime).stuName(stuName).className(className).build();
                lateList.add(lateInfo);
            }
            this.saveBatch(lateList);
            return lateList;
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error("宜搭获取寝室晚归信息报错 ====== code={}，message={}", err.code, err.message);
            }
            throw new BusinessException(err.getMessage());
        }
    }

}
